package com.abhishekduhoon.tfis;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.BufferedReader;
import java.io.FileReader;

import javax.servlet.http.HttpSession;

import com.abhishekduhoon.tfis.Methods;

public class PWMMultipleScan extends HttpServlet {
    
	private static final long serialVersionUID = 1L;
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {

        HttpSession session = request.getSession(true);
        
        String userSequence = request.getParameter("userSequence");
        String error = "error.jsp";
    	
    	if(userSequence.isEmpty()){
    		response.sendRedirect(error);
    	}
    	
    	else{
    		
        userSequence = Methods.reformSequence(userSequence);
        session.setAttribute("userSequence",userSequence);
        String percent = request.getParameter("percent");
        String matrix = request.getParameter("matrix");
        matrix = "pfm/" + matrix;
        int percentScore = Integer.parseInt(percent);
        int totalDetection = 0;
        String line;
        double[][] positionFrequencyMatrix;
        int transcriptionFactorLength;
        double[][] positionWeightMatrix;
        double threshold;
        boolean result;
        String transcriptionFactorId;
        String transcriptionFactorName;
        int userSequenceLength = userSequence.length();
 
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<meta charset='UTF-8'>");
            out.println("<title>TFIS v1.0</title>");
            out.println("<meta name='description' content='Transcription Factor Information System'>");
            out.println("<meta name='keywords' content='TFIS, TF, TFBS'>");
            out.println("<link href='css/style.css' rel='stylesheet' type='text/css'>");
            out.println("</head>");
            out.println("<body>");
            out.println("<div id='wrapper'>");
            out.println("<div id='header'>");
            out.println("<div class='top_banner'>");
            out.println("<h1>TFIS v1.0</h1>");
            out.println("<p>Transcription Factor Information System</p>");
            out.println("</div>");
            out.println("</div>");
            out.println("<div id='page_content'>");
            out.println("<div class='navigation'>");
            out.println("<ul>");
            out.println("<li><a href='index.jsp'>Home</a></li>");
            out.println("<li><a href='about.jsp'>About</a></li>");
            out.println("<li><a href='doc.jsp'>Documentation</a></li>");
            out.println("<li><a href='feedback.jsp'>Feedback</a></li>");
            out.println("<li><a href='support.jsp'>Support</a></li>");
            out.println("</ul>");
            out.println("</div>");
            out.println("<div class='main_section'>");
            out.println("<h2>TFIS v1.0 : Result</h2>");
            out.println("<hr>");
            out.println("<div class='common_content'>");
            
            
            try (BufferedReader br = new BufferedReader(new FileReader(matrix))){
                out.println("<h2>Binding Sites For Following Transcription Factors (TFs) Are Detected :</h2>");
                while ((line = br.readLine()) != null) {
                    if(line.startsWith(">")){
                        String delimiters = "[> ]";
                        String[] lineParts = line.split(delimiters);
                        transcriptionFactorId = lineParts[1];
                        transcriptionFactorName = lineParts[2];
                        line = br.readLine();
                        String A[] = line.split("\\s+");
                        transcriptionFactorLength = A.length;
                        positionFrequencyMatrix = new double[4][transcriptionFactorLength];
                        for(int i = 0; i < transcriptionFactorLength; i++){
                            positionFrequencyMatrix[0][i] = Double.parseDouble(A[i]); 
                        }
                        for(int i = 1; i < 4; i++){
                            line = br.readLine(); 
                            String CTG[] = line.split("\\s+");
                            for(int j = 0; j < transcriptionFactorLength; j++){
                                positionFrequencyMatrix[i][j] = Double.parseDouble(CTG[j]);
                            }
                        }
                        positionWeightMatrix = Methods.pfmConversion(positionFrequencyMatrix, transcriptionFactorLength);
                        threshold = Methods.thresholdCalculator(positionWeightMatrix, transcriptionFactorLength, percentScore);
                        result = Methods.checkOccurence(threshold, positionWeightMatrix, transcriptionFactorLength, userSequenceLength, userSequence);
                        
                        if(result){
                        	if(totalDetection==0){
                                out.print("<a href='TFBSDetail?id="+transcriptionFactorId+"&name="+transcriptionFactorName+"&tfl="+transcriptionFactorLength+"&percent="+percentScore+"'>"+transcriptionFactorName+" ("+transcriptionFactorId+")</a>");
                                totalDetection++;
                        	}
                        	else{
                            out.print(",&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href='TFBSDetail?id="+transcriptionFactorId+"&name="+transcriptionFactorName+"&tfl="+transcriptionFactorLength+"&percent="+percentScore+"'>"+transcriptionFactorName+" ("+transcriptionFactorId+")</a>");
                            totalDetection++;
                        	}
                        }
                    }
                }
            }
            out.println("</br></br>");
            out.println("<h2>Total Transcription Factors (TFs) Detected : "+totalDetection+"</h2>");
            //out.println("<h2>JASPAR Position Frequency Matrix File Used : "+matrix+"</h2>");
            out.println("</div>");
            out.println("</div>");
            out.println("<div id='footer'>Sengupta <i>et al.</i> | Developed and Maintained by <a href='http://www.abhishekduhoon.com' target='_blank'>Abhishek Kumar</a>.");
            out.println("</div>");
            out.println("</div>");
            out.println("</body>");
            out.println("</html>");
        }
    	}
    }
}
    
    

    
    
    

